/*
 * commons is a based project implemented
 * Copyright (C) 2024 Jasmine
 */
package com.easy.web.utils;

import java.io.IOException;
import java.io.Writer;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;

import com.easy.core.domain.pojo.ResultBody;
import com.easy.core.utils.JsonUtils;
import com.easy.web.advice.LogRequestBodyAdvice;

import jakarta.servlet.http.HttpServletResponse;

/**
 * 响应工具类
 *
 * @author Jasmine
 * @since 1.0.0
 */
public class ResponseUtil {
    static Logger log = LoggerFactory.getLogger(LogRequestBodyAdvice.class);

    /**
     * 通过流写到前端
     *
     * @param response
     * @param code 返回状态码
     * @param msg 返回信息
     */
    public static void responseWriter(HttpServletResponse response, int code, String msg) throws IOException {
        response.setStatus(HttpStatus.OK.value());
        response.setContentType("application/json;charset=UTF-8");
        // response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        // response.setCharacterEncoding("utf-8");

        try (Writer writer = response.getWriter()) {
            String result = JsonUtils.getInstance().writeValueAsString(ResultBody.success(code, msg));
            // String result = objectMapper.writeValueAsString(ResultBody.success(code, msg));
            log.info("responseWriter [{} ]", result);
            writer.write(result);
            writer.flush();
        }
    }

    /**
     * 通过流写到前端
     *
     * @param response
     * @param code 返回状态码
     * @param msg 返回信息
     * @param data 数据
     */
    public static void responseWriter(HttpServletResponse response, int code, String msg, Object data)
        throws IOException {
        response.setStatus(HttpStatus.OK.value());
        response.setContentType("application/json;charset=UTF-8");
        try (Writer writer = response.getWriter()) {
            String result = JsonUtils.getInstance().writeValueAsString(ResultBody.success(code, msg, data));
            // String result = objectMapper.writeValueAsString(ResultBody.success(code, msg, data));
            log.info("responseWriter [{} ]", result);
            writer.write(result);
            writer.flush();
        }
    }

    /**
     * 通过流写到前端
     *
     * @param response
     * @param code 返回状态码
     * @param msg 返回信息
     */
    public static void responseWriter(HttpServletResponse response, int responseStatus, int code, String msg)
        throws IOException {
        response.setStatus(responseStatus);
        response.setContentType("application/json;charset=UTF-8");
        try (Writer writer = response.getWriter()) {
            String result = JsonUtils.getInstance().writeValueAsString(ResultBody.success(code, msg, msg));
            // String result = objectMapper.writeValueAsString(ResultBody.success(code, msg));
            log.info("responseWriter [{} ]", result);
            writer.write(result);
            writer.flush();
        }
    }
}
